package com.kaki;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author Kaki_Nakajima
 * @date 2019-07-28
 * @desc xls 读取核心类
 */
public class XLSRearder {

    /**
     * 获取某个文件夹下的所有文件名（包括下级）
     * @param path  原始路径
     * @param fileNameSet 文件名称集合
     */
    public static void getFileNames(String path, HashSet<String> fileNameSet){
        File file = new File(path);
        File[] fileArr = file.listFiles();

        for (int i = 0;i<fileArr.length;i++){
            if(fileArr[i].isFile()){
                fileNameSet.add(fileArr[i].getName());
            }

            //只扫描当前文件下的xls
          /*
            if(fileArr[i].isDirectory()){
                getFileNames(fileArr[i].getAbsolutePath(),fileNameSet);
            }*/
        }
        return;
    }


    /**
     * 读取每一个sheet
     * @param count 统计变量，用于计算“关键字”文件出现的次数
     * @param fileName 当前file名称
     * @param sheet 当前页
     * @param countMap 记录容器
     * @param args 关键字（可变参）
     * @return
     */
    public static HashMap<String,Object> readSheet(int count, String fileName, Sheet sheet,HashMap<String,Object> countMap,String... args ){
        ArrayList<String> currentRowDataList = new ArrayList<String>();

        for (Row row:sheet){
            int unitNum = 0;

            Cell cell = row.getCell(unitNum);

            while (cell !=null){
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                if("".equals(cell.getStringCellValue())){
                    break;
                }

                currentRowDataList.add(cell.getStringCellValue());
                unitNum++;
                cell = row.getCell(unitNum);
            }
        }

        for (String rowData:currentRowDataList){
            for (String arg:args){
                if(rowData.contains(arg)|| arg.equals(rowData)){
                    //记录关键字次数
                    Integer value = (Integer) countMap.get(arg);

                    if(value != null){
                        countMap.put(arg,value+1);
                    }else {
                        countMap.put(arg,1);
                    }
                }
            }
        }
        return countMap;
    }


    /**
     * 读取xls
     * @param fileName
     * @param fileAbsPath
     * @param args
     * @throws IOException
     */
    public static void readXls(String fileName,StringBuilder sb,String fileAbsPath,String...args)throws IOException {

        if(fileAbsPath.lastIndexOf(".")==-1){
            System.out.println("不可以以.开头："+fileAbsPath);
            return;
        }

        //过滤非xls的文件
        String suff = fileAbsPath.substring(fileAbsPath.lastIndexOf("."));
        if(!".xls".equals(suff)){
            System.out.println("非xls文件："+fileAbsPath);
            return;
        }

        int count = 0;
        Integer pageNum = 0;

        HashMap<String,Object> countMap = new HashMap<String, Object>(0);

        HSSFWorkbook workbook = null;
        FileInputStream in = null;

        try {
            in = new FileInputStream(fileAbsPath);
            workbook = new HSSFWorkbook(in);

            ArrayList<String> currentRowDataList = new ArrayList<String>();

            if(workbook!=null){
                String s = "==================>"+fileName+"<=====================\n";
                sb.append(s);

                //得到第一页
                HSSFSheet curSheet = workbook.getSheetAt(pageNum);

                while (curSheet!=null){
                    countMap =readSheet(count,fileName,curSheet,countMap, args);
                    pageNum++;
                    try {
                        curSheet = workbook.getSheetAt(pageNum);
                    }catch (IllegalArgumentException e){
                        if(countMap.size()>0){
                            StringBuilder builder = new StringBuilder("文件："+fileName+"中");
                            Set<Map.Entry<String, Object>> entrySet = countMap.entrySet();

                            for (Map.Entry<String, Object> entry : entrySet) {
                                builder.append(",关键字："+entry.getKey()+"  出现："+ entry.getValue()+"次");
                            }

                            sb.append(builder.toString());
                            sb.append("\n");
                            sb.append("\n");
                            sb.append("\n");

                        }
                        break;
                    }
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(in!=null)in.close();
        }
    }

}
